import Vue from 'vue'
import Vuex from 'vuex'

import { setItem, getItem } from '@/assets/utils/storage.js'
import { getRightList } from '@/assets/api/user/roleRight.js'

Vue.use(Vuex)

// 本地存储 token 保存变量
const TOKEN_KEY = 'HMMM_TOKEN'

export default new Vuex.Store({
  state: {
    // 用户 token
    token: getItem(TOKEN_KEY),
    // 用户管理 - 角色权限列表
    roleRightList: [],
    pageIdx: -1,
    pageList: []
  },
  mutations: {
    // 获取用户登录后的 token
    getToken (state, data) {
      state.token = data
      setItem(TOKEN_KEY, data)
    },
    // 获取角色权限列表
    getRightList (state, data) {
      state.roleRightList = data
    },
    setPageIdx (state, idx) {
      state.pageIdx = idx
    },
    pushPageList (state, obj) {
      state.pageList.push(obj)
    },
    removePageItem (state, idx) {
      state.pageList.splice(idx, 1)
    }
  },
  actions: {
    // 加载角色权限列表
    async loaderRightList ({ commit }) {
      try {
        const { data: res } = await getRightList({
          page: 1,
          pagesize: 7,
          keyword: null
        })
        commit('getRightList', res.list)
      } catch (err) {
        this.$message.error('加载角色权限失败')
      }
    }
  },
  modules: {
  },
  getters: {
    currentPageIndex (state) {
      return state.pageIdx
    }
  }
})
